package com.sunducation.wts.penbox.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cunoraz.gifview.library.GifView;
import com.sunducation.wts.penbox.R;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.base.BaseApplication;
import com.wetao.lib_common.net.cookies.PersistentCookieStore;
import com.wetao.lib_common.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * app 闪屏页
 */
@Route(path = ConstantArouter.PATH_APP_SPLASHACTIVITY)
public class SplashActivity extends AppCompatActivity {

    GifView gif;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //解决返回主界面，重启没有到原界面 方法一
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        //解决返回主界面，重启没有到原界面 方法二
        /*if (!this.isTaskRoot()) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) { // 当前类是从桌面启动的
                    finish();
                    return;
                }
            }
        }*/
        hideBottomUIMenu();
        setContentView(R.layout.activity_splash);

        gif = (GifView) findViewById(R.id.gv_gif);
        permission();

    }



    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }



    private void gotoMainAct(){

        if (PersistentCookieStore.getCookieStore().isLogin()){
            ARouter.getInstance().build(ConstantArouter.PATH_APP_HOMEACTIVITY)
                    .navigation();
        }else {
            ARouter.getInstance().build(ConstantArouter.PATH_COMMON_LOGINACTIVITY).navigation();
        }
        finish();
    }


    @Override
    protected void onStop() {
        super.onStop();
    }


    private static final int PERMISSION_REQUEST_CODE = 102;
    private void permission(){
        List<String> permissionLists = new ArrayList<>();
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.RECORD_AUDIO);
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.ACCESS_NETWORK_STATE);
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.READ_PHONE_STATE);
        }

        if(!permissionLists.isEmpty()){//说明肯定有拒绝的权限
            ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUEST_CODE);
        }else{
            playGif();
            BaseApplication.initTBS();
            //gotoMainAct();
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE: {
                LogUtils.i("-------aa: size = " + grantResults.length);
                if (grantResults.length > 0) {
                    LogUtils.i("-------aa: 1");
                    for (int grantResult : grantResults) {
                        LogUtils.i("-------aa: 2");
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            LogUtils.i("-------aa: 3");
                            finish();
                            return;
                        }
                    }
                    //其他逻辑(这里当权限都同意的话就执行下一步逻辑)
                    LogUtils.i("-------aa: 4");
                    playGif();
                    BaseApplication.initTBS();
                    //gotoMainAct();
                }
            }
                break;
            default:
                break;
        }
    }

    private void playGif(){
        gif.setVisibility(View.VISIBLE);
        gif.setGifResource(R.mipmap.gif_logo);
        gif.play();
        Observable.timer(4500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        gif.pause();
                        //permission();
                        gotoMainAct();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}

